package com.itheima.filter;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
@Slf4j
@WebFilter("/*")
public class TailsFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        // 放行登录请求首先获取url对url进行判断是否包含login
        String url = request.getRequestURL().toString();
        if (url.contains("/login")){
            log.info("登录请求，放行");
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        // 根据token是否为空来判断是否登录
        String token = request.getHeader("token");
        if (token == null|| token.length()==0){
            log.info("未登录，跳转登录页面");
            response.setStatus(401);
            return;
        }
        // 放行
        try {
            log.info("已登录，放行");
            filterChain.doFilter(servletRequest,servletResponse);
        } catch (Exception e) {
            log.info("登录状态已过期，跳转登录页面");
            response.setStatus(401);
            return;
        }
        log.info("请求结束");
        filterChain.doFilter(servletRequest,servletResponse);
        }

    }

